% frame sync simulation after eq
clc;
clear;
close all;

%% tx
PILOT_LEN = 63;
PILOT_TIME = 8;
FSYNC_LEN = 31;
MSG_LEN = 3200;
M = 4;
tx = [];
% pilot for signal detection and frame for sync
pilot_single = m_sequence([1, 0, 0, 0, 0, 1]);
pilot = repmat(pilot_single, PILOT_TIME, 1);
fsync = m_sequence([0, 1, 0, 0, 1]);
% tx signal
for i = 1:100
    msg = sqrt(2) * exp(sqrt(-1) * (2 * pi * randi([0, M - 1], MSG_LEN, 1) / M + pi / 4));
    tx = [tx; pilot; fsync; msg];
end

%% channel
SNR = 25;
h = [1,0.5*exp(1i*pi/6),0.1*exp(-1i*pi/8)];
% rx = awgn(filter(h, 1, [zeros(randi([1000, 5000]), 1); tx]), SNR, 'measured');
rx = awgn(filter(h, 1, [zeros(1000, 1); tx]), SNR, 'measured');
% rx = rx/max(abs(rx));

%% rx
TAP_LEN = 12; %numbers of fir tap
REF_LEN = 6; %reference fir tap index
weight = zeros(TAP_LEN, 1); %fir weight
weight(REF_LEN) = 1;
in = zeros(TAP_LEN, 1); % weight input
y_out = zeros(1, FSYNC_LEN); %  weight output for sync
y_temp = zeros(1,length(rx));

% power calculation related params
power = 0; %signal power
power_sum = 0; %sum of signal power
power_num = 1; %num of signal power added

% detection related params
detect_num = 0; %num of p_num greater than threshold
detect_A = 8; %Tong detection A
detect_threshold = 10;
% flag indicate whether detection finished, 0:no, 1:yes
flag_signal_detected = 0;

% frame sync related params
fs_c = 0;
fs_thre = 50;
fs_temp = [];
fs_delta = MSG_LEN + PILOT_LEN * PILOT_TIME + FSYNC_LEN;
fs_start = 0;
fs_num = 0;

% eq related params
eq_mu = 0.01;
eq_e_temp = [];

for i = 1:length(rx)
    in = [rx(i); in(1:end - 1)];
    y = weight' * in;
    y_temp(i) = y;

    %% signal detection using Tong method
    if (flag_signal_detected == 0)
        power = y * conj(y);
        power_sum = power_sum + power;
        power_num = power_num + 1;
        if (power_num == PILOT_LEN)
            if (power_sum > detect_threshold)
                detect_num = detect_num + 1;
            end
            if (detect_num >= detect_A)
                flag_signal_detected = 1;
            end
            power_sum = 0;
            power_num = 1;
        end
    else
        %% frame sync
        y_out = [y_out(2:end), y];
        fs_c = real(conj(y_out) * fsync);
        fs_temp = [fs_temp,fs_c];
        if(fs_c >= fs_thre )
            eq_in = [zeros(REF_LEN,1);conj(y_out');zeros(REF_LEN-1,1)];
            for index = 1:FSYNC_LEN
                eq_out = weight' * eq_in(index+TAP_LEN-1:-1:index);
                eq_e = fsync(index) - eq_out;
                weight = weight + eq_mu * conj(eq_e) * eq_in(index+TAP_LEN-1:-1:index);
%                 eq_e_temp = [eq_e_temp,abs(eq_e)];
            end
        end
        
    end
end

% figure;
% plot(eq_e_temp);
% xlabel('图1 LMS均衡误差','FontSize',20);

figure;
plot(fs_temp);
xlabel('图2 weighted后的信号和帧同步头相关结果','FontSize',20);
[pks,locs] = findpeaks(fs_temp,'MinPeakDistance',2500);
hold on;plot(locs,pks,'ro');